package org.moon.framework.autoconfigure.openfeign.fallback;

import feign.Target;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cloud.openfeign.FallbackFactory;

/**
 * 默认 FallbackFactory
 * @author moon
 */
public class MoonFallbackFactory<T> implements FallbackFactory<T> {

    private final Target<T> target;

    public MoonFallbackFactory(Target<T> target) {
        this.target = target;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T create(Throwable cause) {
        final Class<T> targetType = target.type();
        final String targetName = target.name();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetType);
        enhancer.setUseCache(true);
        enhancer.setCallback(new MoonFeignFallback<>(targetType, targetName, cause));
        return (T) enhancer.create();
    }
}
